# Copyright (C) 2007 "dbsolution sas" 
# Copyright (C) 2008 "Domenico Chierico"
#
# This file is part of Weebotee.
#
# Weebotee is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Weebotee is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Weebotee.  If not, see <http://www.gnu.org/licenses/>.

from django.template import Library,Node, NodeList
from django.template import resolve_variable
from django.template.loader import get_template
from libs import plug_core
from libs.plug_core.helpers import get_tagged_elem
from apps.core.models.section import Section
from django.template import Context
import re
register = Library()


class Erender(Node):
    def __init__(self, content, style="long"):
        self.elem = content
        self.style = style

    def choose_tmpl(self,elem):
        styles = plug_core.get_all_rend_style(elem.etype)
        if self.style not in styles:
            self.style = "long"
        return plug_core.get_tmpl_from_plug(self.style, elem)

    def get_render_object(self,content, user):
        nodes = NodeList()
        mytmpl = get_template(self.choose_tmpl(content))
        context= Context({'content':content, "user":user})
        
        #for node  in mytmpl:
            #nodes.append(node.render(context))
        
        return mytmpl.nodelist.render(context)
    
    def render(self,context):
        content = resolve_variable(self.elem, context)
        nodes = NodeList()
        if not re.search("Element",content.__class__.__name__):
            if content.__len__() != 1:
                for elem in content:
                    nodes.extend(self.get_render_object(elem, context.get('user')))
            else:
                content = content[0]
                nodes.extend(self.get_render_object(content, context.get('user')))
        else:
            nodes.extend(self.get_render_object(content, context.get('user')))
        return nodes.render(context)
        
 
class Irender(Node):
    def __init__(self, type, text):
        self.type = type
        self.text = text
        
    def render(self, context):
        if self.type != "":
            content = resolve_variable(self.type, context)
        else:
            content = self.text
        nodes = NodeList()
        
        ####
        # Il seguente codice commentato e' stato spostato nella vista che
        # gestisce il form richiesto
        ###
        if not('form' in context):
            slug = plug_core.elem_relative_section(content) 
            initial_data = {
                'owner':context['user'].id,
                'section': Section.objects.get(slug__exact=slug).id,
            }
            f = plug_core.get_form_for_etype(content)
            f = f(initial=initial_data)
            context = {'content':content, 'form':f}

        mytmpl = get_template(plug_core.get_tmpl_from_etype(content, 'input'))
        for node  in mytmpl:
            nodes.append(node.render(context))
        return nodes.render(context)

def element_rendering(parser, token):
    content = token.split_contents()
    # errors
    try:
        style_index = content.index("style")
    except:
        style_index = 0
    style = content[style_index+1][1:-1]
    #fix here
    return Erender(content[1],style)

def addelement_rendering(parser, token):
    content = token.split_contents()
    type = content[1]
    text = ""
    if type == "text":
        text = content[2][1:-1]
        type = ""
    return Irender(type, text)
    
@register.inclusion_tag("widgets/elem_selection.html")
def list_element():
    elems = get_tagged_elem("Element")
    content = { 'elements': []}
    for e in elems:
        content['elements'].append({ 'name': e.__name__ , 
                                     'app': e._meta.app_label})
    return content
    

register.tag('renderize', element_rendering)
register.tag('renderize_input', addelement_rendering)
